
import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/services.dart';
import 'package:rxdart/rxdart.dart';

typedef ImageFrameCallback(Uint8List imageData);

class FlutterScreenCapture {
  static const MethodChannel _channel = const MethodChannel('flutter_screen_capture');
  static BehaviorSubject<bool> _isRunning = BehaviorSubject.seeded(false);
  static List<ImageFrameCallback> _callbacks = [];

  static Future initialize() async {
    _channel.setMethodCallHandler(_methodCallHandler);
  }

  static Future start() async {
    await _channel.invokeMethod('start');
  }

  static Future stop() async {
    await _channel.invokeMethod('stop');
  }

  static Stream<bool> get isRunning => _isRunning.stream;

  static void addFrameListener(ImageFrameCallback callback) {
    if(!_callbacks.contains(callback))
      _callbacks.add(callback);
  }

  static void removeFrameListener(ImageFrameCallback callback) {
    _callbacks.remove(callback);
  }

  static Future _methodCallHandler(MethodCall call) async {
    switch(call.method) {
      case "onFrameUpdate":
        for(ImageFrameCallback callback in _callbacks) {
          callback(call.arguments);
        }
        break;
      case "onStateChanged":
        _isRunning.add(call.arguments);
        break;
      default:
        break;
    }
  }
}
